package com.xxl.job.executor.service.jobhandler;

import com.gxd.esimport.*;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.elasticsearch.action.index.IndexRequest;
import org.springframework.stereotype.Component;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * 任务Handler示例（Bean模式）
 *
 * 开发步骤：
 * 1、继承"IJobHandler"：“com.xxl.job.core.handler.IJobHandler”；
 * 2、注册到Spring容器：添加“@Component”注解，被Spring容器扫描为Bean实例；
 * 3、注册到执行器工厂：添加“@JobHandler(value="自定义jobhandler名称")”注解，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 4、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 *
 * @author xuxueli 2015-12-19 19:43:36
 */
@JobHandler(value="ElasticIncreaseForCaseHandler")
@Component
public class ElasticIncreaseForCaseHandler extends IJobHandler {

    @Override
    public ReturnT<String> execute(String param) throws Exception {
        XxlJobLogger.log("XXL-JOB, elastic for case.");

        try {
            System.out.println("同步开始时间："+new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
            JdbcClientHelper.getConnection();
            tableList.initCaseTables();
            outputThread outputThread = new outputThread(new LinkedBlockingQueue());
            outputThread.initESClient();

            for (Table table:tableList.CaseTables){

                PreparedStatement preparedStatement = null;
                ResultSet resultSet = null;
                try {

                    preparedStatement = JdbcClientHelper.conn.prepareStatement(table.query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
                    preparedStatement.setFetchSize(5000);
                    preparedStatement.setFetchDirection(ResultSet.FETCH_REVERSE);
                    // System.out.println("同步语句："+this.table.query);
                    resultSet = preparedStatement.executeQuery();

                    // 获取列名
                    List<String> columnNameList = new ArrayList<String>();
                    ResultSetMetaData rsmd = resultSet.getMetaData();
                    int count = rsmd.getColumnCount();
                    for (int i = 1; i <= count; i++) {
                        columnNameList.add(rsmd.getColumnName(i));
                    }

                    Map<String, Object> event = new HashMap<String, Object>();
                    // 逐行读取
                    while (resultSet.next()) {
                        Map<String, Object> rowMap = new HashMap<String, Object>();
                        for (String columnName : columnNameList) {
                            rowMap.put(columnName, resultSet.getObject(columnName));
                        }
                        event.put("rowMap", rowMap);
                        event.put("index", table.index);

                        System.out.println(Thread.currentThread().getName()+"入PIPE数据："+String.valueOf(((Map<String, Object>)event.get("rowMap")).get("REQUEST_DATE"))+String.valueOf(((Map<String, Object>)event.get("rowMap")).get("CITY_CODE"))+"++++"+(String)event.get("index")+"++++"+(String)event.get("index")+"++++"+String.valueOf(((Map<String, Object>)event.get("rowMap")).get("ID")));
                        IndexRequest indexRequest = new IndexRequest((String)event.get("index"),(String)event.get("index"),String.valueOf(((Map<String, Object>)event.get("rowMap")).get("ID"))).source((Map<String, Object>)event.get("rowMap"));
                        outputThread.bulkProcessor.add(indexRequest);
                    }



                }catch (SQLSyntaxErrorException e){
                    //e.printStackTrace();
                    System.out.println("线程关闭！！！查血SQl：" + table.query);

                }catch (Exception e) {
                    System.out.println("read failed");
                    e.printStackTrace();
                } finally {
                    //JdbcClientHelper.releaseConnection(JdbcClientHelper.conn, preparedStatement, resultSet);

                    try {
                        preparedStatement.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }

                }

            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return SUCCESS;
    }

}

